package com.kai.steering.data.service.ctl;

import com.kai.steering.data.service.entity.domainObject.QuestionDO;
import com.kai.steering.data.service.entity.dto.QuestionDTO;
import com.kai.steering.data.service.entity.dto.QuestionQueryDTO;
import com.kai.steering.data.service.entity.dto.TestDTO;
import com.kai.steering.data.service.entity.po.Question;
import com.kai.steering.data.service.entity.vo.AnswerVO;
import com.kai.steering.data.service.entity.vo.QuestionVO;
import com.kai.steering.data.service.service.QuestionService;
import com.kai.steering.common.vo.Result;
import com.kai.steering.common.web.ctl.BaseController;
import com.kai.steering.data.service.service.UserQuestionService;
import com.kai.steering.data.service.util.EqualsUtil;
import com.kai.steering.exception.ExcelException;
import com.kai.steering.exception.UimpException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;


import java.io.IOException;
import java.io.Serializable;
import javax.annotation.Resource;
import javax.validation.Valid;

import com.kai.steering.common.vo.Page;
import com.kai.steering.common.web.vo.ReturnCodeExt;
import org.springframework.web.multipart.MultipartFile;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <pre>
 * 题目 前端控制器
 * </pre>
 *
 * @author kai
 * @since 2022-02-23
 */
@Slf4j
@RestController
@RequestMapping("/question")
@Api(tags = "题目 API")
public class QuestionController extends BaseController {
    @Autowired
    private QuestionService questionService;
    @Autowired
    private UserQuestionService userQuestionService;

    @PostMapping
    @ApiOperation(value = "题目-添加")
    public Result<QuestionDO> addQuestion(@Valid @RequestBody QuestionDTO questionDTO) {
//        public Result<QuestionDO> addQuestion() {
//        QuestionDTO questionDTO = new QuestionDTO();
        /**
         *参数检查
         */
        //id
        questionDTO.setQuestionId(null);
        //question
        if (StringUtils.isEmpty(questionDTO.getQuestion())) {
            return Result.failed("题目为空");
        }
        //题目类型分类
        if (StringUtils.isEmpty(questionDTO.getClassificationId())) {
            return Result.failed("类型为空");
        }

        //构建新对象
        QuestionDO questionDO = new QuestionDO(questionDTO);

        QuestionDO question = questionService.saveQuestion(questionDO);
        if (question != null) {
            return Result.ok(question);
        }
        return Result.failed();
    }


    @PutMapping("/{id}")
    @ApiOperation(value = "题目-编辑")
    public Result<Boolean> updateQuestion(@PathVariable("id") Serializable id, @Valid @RequestBody QuestionDTO questionDTO) {

        /**
         * 验证参数
         */
        //id
        if (StringUtils.isEmpty(id.toString())) {
            return Result.failed("id为空");
        }
        questionDTO.setQuestionId(id.toString());
        //question
        if (StringUtils.isEmpty(questionDTO.getQuestion())) {
            return Result.failed("题目为空");
        }
        //题目类型分类
        if (StringUtils.isEmpty(questionDTO.getClassificationId())) {
            return Result.failed("类型为空");
        }
        /**
         * 构建对象
         */
        QuestionDO questionDO = new QuestionDO(questionDTO);
        questionDO.setAnswerDO(null);


        /**
         * 调用服务
         */
        boolean b = questionService.updateQuestion(id, questionDO);
        if (b) {
            return Result.ok();
        }


        return Result.failed();
    }


    @DeleteMapping("/{id}")
    @ApiOperation(value = "题目-删除")
    public Result<Boolean> deleteQuestion(@PathVariable("id") String id) {

        boolean flag = questionService.deleteQuestion(id);
        return Result.ok(flag);

    }


    @PostMapping("/{id}")
    @ApiOperation(value = "题目-详情 questionDetailsExist、answerExist、classificationExist、knowledgeExist、userExist、noteExist")
    public Result<QuestionVO> getQuestion(@PathVariable("id") Serializable id, @RequestBody Map parameterList) {
        if (StringUtils.isEmpty(id.toString())) {
            return Result.failed("id为空");
        }
        HashMap<String, Boolean> parameterMap = new HashMap<>();
        boolean questionDetailsExist = false;
        if (EqualsUtil.objectEquals(parameterList.get("questionDetailsExist"), "1", 1)) {
            questionDetailsExist = true;
        }
        parameterMap.put("questionDetailsExist",questionDetailsExist);
        boolean answerExist = false;
        if (EqualsUtil.objectEquals(parameterList.get("answerExist"), "1", 1)) {
            answerExist = true;
        }
        parameterMap.put("answerExist",answerExist);
        boolean classificationExist = false;
        if (EqualsUtil.objectEquals(parameterList.get("classificationExist"), "1", 1)) {
            classificationExist = true;
        }
        parameterMap.put("classificationExist",classificationExist);
        boolean knowledgeExist = false;
        if (EqualsUtil.objectEquals(parameterList.get("knowledgeExist"), "1", 1)) {
            knowledgeExist = true;
        }
        parameterMap.put("knowledgeExist",knowledgeExist);
        boolean userExist = false;
        boolean noteExist = false;
        if (EqualsUtil.objectEquals(parameterList.get("userExist"), "1", 1)) {
            userExist = true;
            parameterMap.put("userExist",userExist);
            if (EqualsUtil.objectEquals(parameterList.get("noteExist"), "1", 1)) {
                noteExist = true;
            }
            parameterMap.put("noteExist",noteExist);
        }


        QuestionDO questionDO = questionService.getQuestionById(id , parameterMap);
        if (questionDO == null || StringUtils.isEmpty(questionDO.getQuestionId())) {
            return Result.failed("id[" + id + "]对象不存在");
        }


        QuestionVO questionVO = new QuestionVO(questionDO);


        return Result.ok(questionVO);
    }


    @PostMapping("/list")
    @ApiOperation(value = "题目-综合查询")
    public Result<Page<QuestionVO>> getQuestionPageList(@Valid @RequestBody QuestionQueryDTO questionQueryDTO) {
        Page<QuestionVO> paging = questionService.getQuestionPageList(questionQueryDTO);
        return Result.ok(paging);
    }


//    @GetMapping("/list")
//    @ApiOperation(value = "题目-全部列表")
//    public Result<List<QuestionVO>> getQuestionAllList() {
//
//        List<QuestionVO> list = null;
//        return Result.ok(list);
//    }

    @PostMapping("/exportQuestion")
    @ApiOperation(value = "题目-导出题目")
    public Result<Boolean> exportQuestion(List<String> questionIds) {
        return Result.ok(questionService.exportQuestion(questionIds));
    }

    @PostMapping("/importQuestion")
    @ApiOperation(value = "题目-导入题目")
    public ResponseEntity<Resource> importQuestion(@RequestParam("file") MultipartFile file) {
        List<ExcelException> excelExceptions = questionService.importQuestion(file, 0, 0);
        if (excelExceptions.size() > 0) {
            try {
                ResponseEntity responseEntity = UimpException.generateResponse(file, excelExceptions);
                return responseEntity;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        ResponseEntity successResource = ResponseEntity.ok("导入成功");
        return successResource;
    }

    @PostMapping("/test/{test_id}")
    @ApiOperation(value = "试卷-题目列表")
    public Result<List<QuestionVO>> getTestquestion(@PathVariable("test_id") Serializable testId, @RequestBody Map parameterList) {
        HashMap<String, Boolean> parameterMap = new HashMap<>();


        boolean questionUserExist = false;
        if (EqualsUtil.objectEquals(parameterList.get("questionUserExist"), "1", 1)) {
            questionUserExist = true;
        }
        parameterMap.put("questionUserExist",questionUserExist);
        boolean questionDetailsExist = false;
        if (EqualsUtil.objectEquals(parameterList.get("questionDetailsExist"), "1", 1)) {
            questionDetailsExist = true;
        }
        parameterMap.put("questionDetailsExist",questionDetailsExist);
        List<QuestionDO> list = questionService.getTestquestion(testId, parameterMap);

        List<QuestionVO> questionVO = QuestionVO.convertWarehouseVOS(list);
        return Result.ok(questionVO);
    }

    @GetMapping("/collection/{id}/{result}")
    @ApiOperation(value = "收藏题目")
    public Result<Boolean> collection(@PathVariable("id") Serializable id, @PathVariable("result") Serializable result) {
        String b = "1";
        if (result.toString().equals("1")) {
            b = "1";
        } else {
            b = "0";
        }
        Boolean aBoolean = questionService.questionService(id.toString(), b);
        return Result.ok(aBoolean);

    }

    @GetMapping("/correctJudgment/{id}/{answerId}/{result}")
    @ApiOperation(value = "判断回答正确与否")
    public Result<Boolean> correctJudgment(@PathVariable("id") Serializable id,@PathVariable("answerId") Serializable answerId, @PathVariable("result") Serializable result) {
        Boolean aBoolean = questionService.correctJudgment(id.toString(),answerId.toString(),result.toString());
        return Result.ok(aBoolean);
    }
}